/*
 * Copyright 2013 Rivaldo.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jety.server.transport;

import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Class to be instantiated by the servlet.
 * @author Rivaldo
 */
public class HttpServerExecutor {

    private HttpServer server;

    private HttpServerHandler handlerManager;
    private static final Logger LOG = LoggerFactory.getLogger(HttpServerExecutor.class);

    /**
     * Create a new server.
     */
    public HttpServerExecutor() {
        this.handlerManager = new HttpServerHandler();
    }

    /**
     * Add a new handler class to treat the client request.
     * @param <T> the handler class type
     * @param name a name to identfy the handler
     * @param handler an instance of the handle
     * @param classes the interfaces implemented by the handler
     * @throws RuntimeException erro while creating the handler
     */
    public <T> void addHandler(String name, T handler, Class<T>... classes) throws RuntimeException {
        handlerManager.addHandler(name, handler, classes);
    }

    public void start() throws IOException {
        ExecutorService es = Executors.newCachedThreadPool();

        server = HttpServer.create(new InetSocketAddress(8000), 0);
        server.createContext("/test", handlerManager);
        server.setExecutor(es); // creates a default executor
        server.start();
    }
}
